package cn.mg.framework.exception;

import cn.mg.framework.response.CommonCode;
import cn.mg.framework.response.PlatformErrorResult;
import cn.mg.framework.response.ResponseCode;
import cn.mg.framework.util.common.MapBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

/**
 * 统一异常捕获类
 *
 * @author hezhaoming
 * @date 2019-10-31
 */
@ControllerAdvice
@Slf4j
public class ExceptionCatch {

    /**
     * 定义map的builder对象，去构建ImmutableMap
     */
    protected static MapBuilder<Class< ? extends Throwable>, ResponseCode> builder = new MapBuilder.Builder<Class< ? extends Throwable>, ResponseCode>().build();

    /**
     * 定义map，配置异常类型所对应的错误代码
     */
    private static Map<Class<? extends Throwable>, ResponseCode> EXCEPTIONS;

    static {
        //定义异常类型所对应的错误代码
        builder.put(HttpMessageNotReadableException.class, CommonCode.SERVER_ERROR);
    }

    /**
     * 捕获CustomException此类异常
     *
     * @param businessException
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public PlatformErrorResult customException(BusinessException businessException) {
        businessException.printStackTrace();
        //记录日志
        log.error("<== catch exception:{}", businessException.getMessage());
        return PlatformErrorResult.failure(businessException);
    }

    /**
     * 捕获Exception此类异常
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public PlatformErrorResult exception(Exception exception) {
        exception.printStackTrace();
        //记录日志
        log.error("<<=== catch exception:[{}]===>>", exception);
        if (EXCEPTIONS == null) {
            //EXCEPTIONS构建成功
            EXCEPTIONS = builder.build();
        }
        //从EXCEPTIONS中找异常类型所对应的错误代码，如果找到了将错误代码响应给用户，如果找不到给用户响应99999异常
        ResponseCode resultCode = EXCEPTIONS.get(exception.getClass());
        if (resultCode != null) {
            return PlatformErrorResult.failure(resultCode, exception);
        } else {
            //返回99999异常
            return PlatformErrorResult.failure(CommonCode.SERVER_ERROR, exception);
        }
    }
}
